package com.emersonprocess.danpacmobile.utils;

import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

import com.emersonprocess.danpacmobile.R;

public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
	ImageView bmImage;
	AnimationDrawable frameAnimation;

	public DownloadImageTask(ImageView bmImage) {
		this.bmImage = bmImage;
	}
	
	

	@Override
	protected void onPreExecute() {
		this.bmImage.setImageResource(R.drawable.spin_animation);
		
		 // Get the background, which has been compiled to an AnimationDrawable object.
		 frameAnimation = (AnimationDrawable) bmImage.getDrawable();

		 // Start the animation (looped playback by default).
		 frameAnimation.start();
	}



	protected Bitmap doInBackground(String... urls) {
		String urldisplay = urls[0];
		urldisplay = urldisplay.trim().replaceAll(" ", "%20");
		Bitmap mIcon11 = null;
		try {
			InputStream in = new java.net.URL(urldisplay).openStream();
			mIcon11 = BitmapFactory.decodeStream(in);
		} catch (Exception e) {
			Log.e("Error", e.getMessage());
			e.printStackTrace();
		}
		return mIcon11;
	}

	protected void onPostExecute(Bitmap result) {
		if(frameAnimation!=null){
			frameAnimation.stop();
			this.bmImage.setBackgroundResource(0);
		}
		if (result != null && bmImage!=null)
			bmImage.setImageBitmap(result);
		if (bmImage.getRootView() != null)
			bmImage.getRootView().invalidate();
	}
}